package lex.dm.ui.dt;

import java.util.ArrayList;

import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.AbstractTableModel;

import org.lex.utils.StateChangeSupport;

import lex.dm.utils.FieldInfo;

public class FieldsTableModel extends AbstractTableModel
{
	private static final String[] COLUMN_NAMES = { "", "Name", "Type" };
	private boolean[] selected = new boolean[0];
	private FieldInfo[] fields = new FieldInfo[0];
	private StateChangeSupport scs = new StateChangeSupport();

	public FieldsTableModel()
	{
		this.setContent( new FieldInfo[0] );
	}
	
	public String[] getSelectedFields()
	{
		ArrayList<String> list = new ArrayList<String>(fields.length/2+1);
		for( int i=0;i<selected.length;i++)
			if( true == selected[i] )
				list.add( fields[i].getName() );
		return list.toArray( new String[0] );
	}

	public void setContent( FieldInfo[] fields )
	{
		this.fields = fields;
		this.selected = new boolean[fields.length];
		java.util.Arrays.fill( selected, false );
		this.fireTableDataChanged();
	}
	
	public void addContentChangedListener( ChangeListener l )
	{
		this.scs.addChangeListener( l );
	}

	public int getColumnCount()
	{
		return COLUMN_NAMES.length;
	}

	public int getRowCount()
	{
		return fields.length;
	}

	@Override
	public Class<?> getColumnClass( int column )
	{
		if( 0 == column )
			return Boolean.class;
		else
			return String.class;
	}

	@Override
	public String getColumnName( int column )
	{
		return COLUMN_NAMES[column];
	}

	public Object getValueAt( int row, int column )
	{
		switch( column )
		{
		case 0:
			return selected[row];
		case 1:
			return fields[row].getName();
		case 2:
			return fields[row].getTypeName();
		}
		return null;
	}

	@Override
	public boolean isCellEditable( int row, int column )
	{
		return 0 == column;
	}

	@Override
	public void setValueAt( Object aValue, int row, int column )
	{
		if( 0 == column )
		{
			this.selected[row] = Boolean.valueOf( aValue.toString() );
			this.fireTableContentChanged();
		}
	}
	
	private ChangeEvent e = new ChangeEvent(this);
	private void fireTableContentChanged()
	{
		this.scs.fireStateChanged( e );
	}
}
